package com.qimingyu.array.binarysearch;

import java.util.Arrays;

/**
 * 35. 搜索插入位置
 * 简单
 * 2.1K
 * 相关企业
 * 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
 * <p>
 * 请必须使用时间复杂度为 O(log n) 的算法。
 * <p>
 * 示例 1:
 * <p>
 * 输入: nums = [1,3,5,6], target = 5
 * 输出: 2
 * 示例 2:
 * <p>
 * 输入: nums = [1,3,5,6], target = 2
 * 输出: 1
 * 示例 3:
 * <p>
 * 输入: nums = [1,3,5,6], target = 7
 * 输出: 4
 * <p>
 * 提示:
 * <p>
 * 1 <= nums.length <= 104
 * -104 <= nums[i] <= 104
 * nums 为 无重复元素 的 升序 排列数组
 * -104 <= target <= 104
 */
public class SearchInsert {
    public int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int candidate = -1;
        int middle = 0;
        while (left <= right) {
            middle = (right + left) >>> 1;
            int middleNum = nums[middle];
            if (target < middleNum) {
                right = middle - 1;
            } else if (middleNum < target) {
                left = middle + 1;
            } else {
                candidate = middle;
                right = middle - 1;
            }
        }
        return candidate == -1 ? left  : candidate;
    }


    public int searchInsert2(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int middle = (right + left) >>> 1;
            int middleNum = nums[middle];
            if (target < middleNum) {
                right = middle - 1;
            } else if (middleNum < target) {
                left = middle + 1;
            } else {
                return middle;
            }
        }
        return left;
    }
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 2, 2, 2, 5, 9, 10, 11};
        int[] nums = {1};
        int[] nums2 = {1,3,5,6};

//        System.out.println(new SearchInsert().searchInsert(arr, 2));
//        System.out.println(new SearchInsert().searchInsert(nums, 0));
       // System.out.println(new SearchInsert().searchInsert(nums, 1));
        System.out.println(new SearchInsert().searchInsert(nums2, 2));
//        System.out.println(Arrays.binarySearch(nums, 0));
    }


}
